package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/10/24.
 */
@Controller
@RequestMapping(value = "page/leadStu")
public class LeadStudentAssessController {

    @Autowired
    private TokenController tokenController;

    @Autowired
    private CourseStuAttendanceService courseStuAttendanceService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private LeadershipService leadershipService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private EvaluateTeacherService evaluateTeacherService;

    /**
     * 旧学生测评查询
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectAssess")
    @ResponseBody
    public synchronized Object selectAssess(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Map<String, Object> objectMap1 = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        String leadId = request.getParameter("leadId");
        String college = request.getParameter("college");
        String major = request.getParameter("major");
        Integer roleId = Integer.parseInt(request.getParameter("roleId"));
        String token = request.getParameter("token");
        if (tokenController.tokenLead(leadId, roleId, token) != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, -7);
            Date monday = c.getTime();
            String preMonday = sdf.format(monday);

            if (college != null && !college.equals("")) {

                StudentEvaluateStatistics studentEvaluateStatistics = new StudentEvaluateStatistics();
                studentEvaluateStatistics.setStudentmajor(major);
                studentEvaluateStatistics.setColleaguename(college);
                studentEvaluateStatistics.setStatisticstime(preMonday);
                List<StudentEvaluateStatistics> studentEvaluateStatisticsList = leadershipService.selectStudentEvaluateStatistics(studentEvaluateStatistics);

                System.out.println("长度：" + studentEvaluateStatisticsList.size());
                Map map1 = new HashMap();
                if (studentEvaluateStatisticsList.size() > 0) {
                    float percentageCompleteSum = 0f;
                    for (int a = 0; a < studentEvaluateStatisticsList.size(); a++) {
                        float percentageCompletes = studentEvaluateStatisticsList.get(a).getPercentagecomplete();
                        percentageCompleteSum += percentageCompletes;
                    }

                    float percentageComplete = percentageCompleteSum / studentEvaluateStatisticsList.size();
                    System.out.println("和：" + percentageCompleteSum + "   率：" + percentageComplete);
//                Math.round(perpercentageCompleteSum/studentEvaluateStatisticsList.size()*100)/100;
                    map1.put("percentageComplete", percentageComplete);
                    objectMap1.put("reviewCompletion", map1);
                } else {
                    map1.put("percentageComplete", 0);
                    objectMap1.put("reviewCompletion", map1);
                }

                int n = 0;
                int m = 0;
                CourseStuAttendance courseStuAttendance = new CourseStuAttendance();
                if (major != null && !major.equals("")) {
                    Student student = new Student();
                    student.setStudentmajor(major);
                    student.setStudentremarks("离开");
                    List<Student> studentList = studentService.selectByMa(student);
                    if (studentList != null && studentList.size() > 0) {
                        for (int i = 0; i < studentList.size(); i++) {
                            student = studentList.get(i);
                            courseStuAttendance.setStuid(student.getStudentid());
                            n = courseStuAttendanceService.countLimitNumStu(courseStuAttendance) + n;
                            courseStuAttendance.setAttendancecontent("0");
                            m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance) + m;
                        }
                    }
                    map.put("numSum", n);
                    map.put("numC", m);
                } else {
                    Student student = new Student();
                    student.setStudentcollege(college);
                    student.setStudentremarks("离开");
                    List<Student> studentList = studentService.selectByCo(student);
                    if (studentList != null && studentList.size() > 0) {
                        for (int i = 0; i < studentList.size(); i++) {
                            student = studentList.get(i);
                            courseStuAttendance.setStuid(student.getStudentid());
                            n = courseStuAttendanceService.countLimitNumStu(courseStuAttendance) + n;
                            courseStuAttendance.setAttendancecontent("0");
                            m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance) + m;
                        }
                    }
                    map.put("numSum", n);
                    map.put("numC", m);
                }
                objectMap1.put("attendance", map);
                objectMap.put("data", objectMap1);
                objectMap.put("message", "成功");
                objectMap.put("code", 200);
            } else {
                Map map1 = new HashMap();
                System.out.println("进入else");
                StudentEvaluateStatistics studentEvaluateStatistics = new StudentEvaluateStatistics();
                studentEvaluateStatistics.setStatisticstime(preMonday);
                List<StudentEvaluateStatistics> studentEvaluateStatisticsList = leadershipService.selectStudentEvaluateStatistics(studentEvaluateStatistics);

                System.out.println("长度：" + studentEvaluateStatisticsList.size());
                if (studentEvaluateStatisticsList.size() > 0) {
                    float percentageCompleteSum = 0f;
                    for (int a = 0; a < studentEvaluateStatisticsList.size(); a++) {
                        float percentageCompletes = studentEvaluateStatisticsList.get(a).getPercentagecomplete();
                        percentageCompleteSum += percentageCompletes;
                    }

                    float percentageComplete = percentageCompleteSum / studentEvaluateStatisticsList.size();
                    System.out.println("和：" + percentageCompleteSum + "   率：" + percentageComplete);
//                Math.round(perpercentageCompleteSum/studentEvaluateStatisticsList.size()*100)/100;
                    map1.put("percentageComplete", percentageComplete);
                    objectMap1.put("reviewCompletion", map1);
                } else {
                    map1.put("percentageComplete", 0);
                    objectMap1.put("reviewCompletion", map1);
                }

                int num = courseStuAttendanceService.countLimitNumZ();
                CourseStuAttendance courseStuAttendance = new CourseStuAttendance();
                courseStuAttendance.setAttendancecontent("0");
                int num1 = courseStuAttendanceService.countLimitNumZBy(courseStuAttendance);
                map.put("numSum", num);
                map.put("numC", num1);
                objectMap1.put("attendance", map);
                objectMap.put("data", objectMap1);
                objectMap.put("message", "成功");
                objectMap.put("code", 200);
            }
        } else {
            objectMap.put("message", "此用户没有权限做此操作");
            objectMap.put("code", 203);
        }
        return objectMap;
    }

    /**
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectAssessDate")
    @ResponseBody
    public synchronized Object selectAssessDate(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Map<String, Object> objectMap1 = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        String leadId = request.getParameter("leadId");
        String college = request.getParameter("college");
        String major = request.getParameter("major");
        Integer roleId = Integer.parseInt(request.getParameter("roleId"));
        String token = request.getParameter("token");
        List<Student> studentListCo = studentService.selectCollegeByAll();//获取学院
        List<Student> studentListMa = studentService.selectMajorByAll("");//获取和学院相关专业
        if (tokenController.tokenLead(leadId, roleId, token) != null) {
            if (college != null && !college.equals("")) {
                int n = 0;
                int m = 0;
                CourseStuAttendance courseStuAttendance = new CourseStuAttendance();
                if (major != null && !major.equals("")) {
                    Student student = new Student();
                    student.setStudentmajor(major);
                    student.setStudentremarks("离开");
                    List<Student> studentList = studentService.selectByMa(student);
                    if (studentList != null && studentList.size() > 0) {
                        for (int i = 0; i < studentList.size(); i++) {
                            student = studentList.get(i);
                            courseStuAttendance.setStuid(student.getStudentid());
                            n = courseStuAttendanceService.countLimitNumStu(courseStuAttendance) + n;
                            courseStuAttendance.setAttendancecontent("0");
                            m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance) + m;
                        }
                    }
                    map.put("numSum", n);
                    map.put("numC", m);
                } else {
                    Student student = new Student();
                    student.setStudentcollege(college);
                    student.setStudentremarks("离开");
                    List<Student> studentList = studentService.selectByCo(student);
                    if (studentList != null && studentList.size() > 0) {
                        for (int i = 0; i < studentList.size(); i++) {
                            student = studentList.get(i);
                            courseStuAttendance.setStuid(student.getStudentid());
                            n = courseStuAttendanceService.countLimitNumStu(courseStuAttendance) + n;
                            courseStuAttendance.setAttendancecontent("0");
                            m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance) + m;
                        }
                    }
                    map.put("numSum", n);
                    map.put("numC", m);
                }
                objectMap1.put("attendance", map);
                objectMap.put("data", objectMap1);
                objectMap.put("message", "成功");
                objectMap.put("code", 200);
            } else {
                int num = courseStuAttendanceService.countLimitNumZ();
                CourseStuAttendance courseStuAttendance = new CourseStuAttendance();
                courseStuAttendance.setAttendancecontent("0");
                int num1 = courseStuAttendanceService.countLimitNumZBy(courseStuAttendance);
                map.put("numSum", num);
                map.put("numC", num1);
                objectMap1.put("attendance", map);
                objectMap.put("data", objectMap1);
                objectMap.put("message", "成功");
                objectMap.put("code", 200);
            }
        } else {
            objectMap.put("message", "此用户没有权限做此操作");
            objectMap.put("code", 203);
        }
        return objectMap;
    }

    /**
     * 新学生的考勤评价
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectAssessNew")
    @ResponseBody
    public synchronized Object selectAssessNew(HttpServletRequest request) {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        Map<String, Object> objectMap1;
        Map<String, Object> objectMap2 = new HashMap<String, Object>();
        Map<String, Object> map;
        String leadId = request.getParameter("leadId");
        String college = request.getParameter("college");
        Integer roleId = Integer.parseInt(request.getParameter("roleId"));
        String token = request.getParameter("token");
//        System.out.println("selectAssessNew" + roleId);
//        List<Student> studentListCo = studentService.selectCollegeByAll();//获取学院
//        List<Student> studentListMa = studentService.selectMajorByAll("");//获取和学院相关专业
        if (tokenController.tokenLead(leadId, roleId, token) != null) {
            List<Map> mapList = new ArrayList<Map>();
            int n;
            int m;
            if (college != null && !college.equals("")) {
                List<Student> studentListMa = studentService.selectMajorByAll(college);
                if (studentListMa != null && studentListMa.size() > 0) {
                    CourseStuAttendance courseStuAttendance;
                    for (int i1 = 0; studentListMa.size() > i1; i1++) {//根据学院循环专业的数据
                        courseStuAttendance = new CourseStuAttendance();
                        objectMap1 = new HashMap<String, Object>();
                        map = new HashMap<String, Object>();
                        courseStuAttendance.setStudentcollege(college);
                        courseStuAttendance.setStudentmajor(studentListMa.get(i1).getStudentmajor());
                        n = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance);
                        courseStuAttendance.setAttendancecontent("0");
                        m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance);
                        map.put("numSum", n);
                        map.put("numC", m);
                        objectMap1.put("major", map);
                        objectMap1.put("majorName", studentListMa.get(i1).getStudentmajor());
                        mapList.add(objectMap1);
                    }
//                    objectMap1.put("major", mapList);
                    objectMap.put("data", mapList);
                    objectMap.put("message", "成功");
                    objectMap.put("code", 200);
                } else {
                    objectMap.put("message", "此学院没有找到专业");
                    objectMap.put("code", 205);
                }
            } else {
                Map<String, Object> map2 = new HashMap<String, Object>();
                objectMap1 = new HashMap<String, Object>();
                int num = courseStuAttendanceService.countLimitNumZ();
                CourseStuAttendance courseStuAttendance = new CourseStuAttendance();
                courseStuAttendance.setAttendancecontent("0");
                int num1 = courseStuAttendanceService.countLimitNumZBy(courseStuAttendance);
                map2.put("numSum", num);
                map2.put("numC", num1);
                objectMap2.put("school",map2);
                if (roleId == 5) {
                    List<Student> studentListCo = studentService.selectCollegeByAll();
                    if (studentListCo != null && studentListCo.size() > 0) {
                        for (int i = 0; i < studentListCo.size(); i++) {//循环学院
                            courseStuAttendance = new CourseStuAttendance();
                            objectMap1 = new HashMap<String, Object>();
                            map = new HashMap<String, Object>();
                            courseStuAttendance.setStudentcollege(studentListCo.get(i).getStudentcollege());
                            n = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance);
                            courseStuAttendance.setAttendancecontent("0");
                            m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance);
                            map.put("numSum", n);
                            map.put("numC", m);
                            objectMap1.put("college", map);
                            objectMap1.put("collegeName", studentListCo.get(i).getStudentcollege());
                            mapList.add(objectMap1);
                        }
                        objectMap2.put("colleges",mapList);
                        objectMap.put("data", objectMap2);
                        objectMap.put("message", "成功");
                        objectMap.put("code", 200);
                    } else {
                        objectMap.put("message", "没有找到学院");
                        objectMap.put("code", 205);
                    }
                } else {
                    Teacher teacher = teacherService.serlectTeacher(leadId);
                    courseStuAttendance = new CourseStuAttendance();
                    objectMap1 = new HashMap<String, Object>();
                    map = new HashMap<String, Object>();
                    courseStuAttendance.setStudentcollege(teacher.getTeachercollege());
                    n = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance);
                    courseStuAttendance.setAttendancecontent("0");
                    m = courseStuAttendanceService.countLimitNumStuA(courseStuAttendance);
                    map.put("numSum", n);
                    map.put("numC", m);
                    objectMap1.put("college", map);
                    objectMap1.put("collegeName", teacher.getTeachercollege());
                    mapList.add(objectMap1);
                    objectMap2.put("colleges",mapList);
                    objectMap.put("data", objectMap2);
                    objectMap.put("message", "成功");
                    objectMap.put("code", 200);
                }
            }
        } else {
            objectMap.put("message", "此用户没有权限做此操作");
            objectMap.put("code", 203);
        }
        return objectMap;
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePassword")
    public synchronized @ResponseBody Map<String,Object> updatePassword(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
//        Map<String, Object> objectMap = new HashMap<String, Object>();
        String teacherId = request.getParameter("leadId");//领导
        Integer roleId = Integer.parseInt(request.getParameter("roleId"));
        String password = request.getParameter("password");//老密码
        String password1 = request.getParameter("password1");//新密码
        String password2 = request.getParameter("password2");//验证新密码
        String token = request.getParameter("token");
        TeacherData teacherData;
        System.out.println(teacherId+","+token);
        teacherData = (TeacherData) tokenController.tokenLead(teacherId,roleId, token);
        if (teacherData != null) {
            if (DigestUtils.md5Hex(password).equals(teacherData.getTeacherpassword())) {
                System.out.println(password+",");
                if (password1.equals(password2)) {
                    teacherData = new TeacherData();
                    teacherData.setTeacherid(teacherId);
                    teacherData.setTeacherpassword(DigestUtils.md5Hex(password1));
                    if (teacherService.updateTeacher(teacherData) > 0) {
                        map.put("code", 200);
                        map.put("message", "修改成功");
//                        map.put("data","");
                    } else {
                        map.put("code", 201);
                        map.put("message", "修改失败,请核对信息是否正确");
//                        map.put("data","");
                    }
                } else {

                    map.put("code", 202);
                    map.put("message", "两次密码不一致");
//                    map.put("data","");
                }
            } else {
                map.put("code", 203);
                map.put("message", "密码不正确");
//                map.put("data","");
            }
        }else {
            map.put("code", 204);
            map.put("message", "您暂无权限做此操作");
//            map.put("data","");

        }
        return map;
    }


    /**
     *新教评完成率
     * @param request
     * @return
     */
    @RequestMapping(value = "evaluatePercentageComplete")
    public synchronized @ResponseBody
    Map<String,Object> evaluatePercentageComplete(HttpServletRequest request)throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//可以方便地修改日期格式
        String nowTime = dateFormat.format( now );//时间

        long weekNum=0;
        int dayForWeek1 = 0;
        //这里需要计算获取  ！！！查出第几周，周几！
        TermBeginsTime termBeginsTime=evaluateTeacherService.selectTermBeginsTime();//查出开学时间

        if (termBeginsTime!=null){
            String termTime=termBeginsTime.getTermbeginstime();

            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");

            Date a1 = format .parse(nowTime);
//            System.out.println("a1:"+a1);
            Date b1 = format .parse(termTime);
//            System.out.println("b1:"+b1);
            weekNum = (a1.getTime()-b1.getTime())/(7*24*60*60*1000)+1;
//            System.out.println("weekNum:"+weekNum);
//                    /(7*24*60*60*1000)+1;

            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(format.parse(nowTime));
            c2.setTime(format.parse(termTime));

            if(c1.get(Calendar.DAY_OF_WEEK) == 1){
                dayForWeek1 = 7;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 2){
                dayForWeek1 = 1;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 3){
                dayForWeek1 = 2;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 4){
                dayForWeek1 = 3;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 5){
                dayForWeek1 = 4;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 6){
                dayForWeek1 = 5;
            }else if (c1.get(Calendar.DAY_OF_WEEK) == 7){
                dayForWeek1 = 6;
            }
            int dayForWeek2 = 0;
            if(c2.get(Calendar.DAY_OF_WEEK) == 1){
                dayForWeek2 = 7;
            }else{
                dayForWeek2 = c2.get(Calendar.DAY_OF_WEEK) - 1;
            }

            if (dayForWeek1<dayForWeek2){
                weekNum=weekNum+1;
            }
        }
        System.out.println("当前为：" + weekNum);
//        weekNum=14;//暂时设置为第14周！！！！！！！！

        StudentEvaluateStatistics studentEvaluateStatistics=new StudentEvaluateStatistics();

        String collegeName= request.getParameter("collegeName");//学院名  可以为空
        String studentMajor=request.getParameter("studentMajor");//专业名  可以为空

        String teacherId=request.getParameter("teacherId");
        Integer roleId = Integer.parseInt(request.getParameter("roleId"));
        String token=request.getParameter("token");

        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.tokenLead(teacherId, roleId, token);
        if (teacherData==null){
            map.put("code", 202);
            map.put("message", "您暂无权限做此操作");
            return map;
        }

        studentEvaluateStatistics.setColleaguename(collegeName);
        studentEvaluateStatistics.setStudentmajor(studentMajor);
        studentEvaluateStatistics.setWeeknum((int) weekNum-1);

        List<StudentEvaluateStatistics> studentEvaluateStatisticsList=leadershipService.selectStudentEvaluateStatistics(studentEvaluateStatistics);


        if (studentEvaluateStatisticsList.size()>0){

            if (collegeName.equals("")||collegeName==null){//如果没有传入学院，说明查全部
                Map<String,Object> map1=new HashMap<String,Object>();
                int maxSum=0,realSum=0;
                for (StudentEvaluateStatistics studentEvaluateStatistics1:studentEvaluateStatisticsList){
                    if (map1.containsKey(studentEvaluateStatistics1.getColleaguename())){
                        String[] evaluateNum= map1.get(studentEvaluateStatistics1.getColleaguename()).toString().split("/");
//                        System.out.println(evaluateNum[0]+"====="+studentEvaluateStatistics1.getMaxevaluatenum());
                        int maxEvaluateNum=Integer.parseInt(evaluateNum[0])+studentEvaluateStatistics1.getMaxevaluatenum();
                        int realEvaluateNum=Integer.parseInt(evaluateNum[1])+studentEvaluateStatistics1.getRealevaluatenum();
                        map1.put(studentEvaluateStatistics1.getColleaguename(),maxEvaluateNum+"/"+realEvaluateNum);
                        maxSum+=studentEvaluateStatistics1.getMaxevaluatenum();
                        realSum+=studentEvaluateStatistics1.getRealevaluatenum();
                    }else {
                        map1.put(studentEvaluateStatistics1.getColleaguename(),studentEvaluateStatistics1.getMaxevaluatenum()+"/"+studentEvaluateStatistics1.getRealevaluatenum());
                        maxSum+=studentEvaluateStatistics1.getMaxevaluatenum();
                        realSum+=studentEvaluateStatistics1.getRealevaluatenum();
                    }
                }
                map1.put("avg",maxSum+"/"+realSum);//平均教评率

                Map<String,Object> map2;
                List<Map> mapList=new ArrayList<Map>();
                for (Map.Entry<String, Object> entry : map1.entrySet()) {
                    map2=new HashMap<String, Object>();
                    if (entry.getKey().equals("avg")){
                        map2.put("sign",1);//标记该条数据为平均分
                        map2.put("collegeName","平均分");
                    }else {
                        map2.put("sign",2);//标记该数据为学院分
                        map2.put("collegeName",entry.getKey());
                    }

                    String[] evaluateNum=entry.getValue().toString().split("/");
                    map2.put("maxEvaluateNum",Integer.parseInt(evaluateNum[0]));
                    map2.put("realEvaluateNum",Integer.parseInt(evaluateNum[1]));

                    mapList.add(map2);
                }
                map.put("code",200);
                map.put("message","查询统计结果成功");
                map.put("data",mapList);

            }else {//有学院  说明查的是该学院下的专业统计
                System.out.println("进入2  学院不为空");
                Map<String, Object> map1;
                int maxSum=0,realSum=0;
                List<Map> mapList=new ArrayList<Map>();
                for (StudentEvaluateStatistics studentEvaluateStatistics1 : studentEvaluateStatisticsList) {
                    map1=new HashMap<String, Object>();
                    map1.put("majorName",studentEvaluateStatistics1.getStudentmajor());
                    map1.put("sign",3);
                    map1.put("maxEvaluateNum",studentEvaluateStatistics1.getMaxevaluatenum());
                    map1.put("realEvaluateNum",studentEvaluateStatistics1.getRealevaluatenum());

                    maxSum+=studentEvaluateStatistics1.getMaxevaluatenum();
                    realSum+=studentEvaluateStatistics1.getRealevaluatenum();
                    mapList.add(map1);
                }
                map1=new HashMap<String, Object>();
                map1.put("majorName","平均分");
                map1.put("sign",2);
                map1.put("maxEvaluateNum",maxSum);
                map1.put("realEvaluateNum",realSum);
                mapList.add(map1);


                map.put("code",200);
                map.put("message","查询统计结果成功");
                map.put("data",mapList);
            }

        }else {
            //查询无结果
            map.put("code",201);
            map.put("message","数据正在统计...");
        }

        return map;
    }

}
